import { ResourceTransform, LcDocument, ITypeEntity } from './ResourceTransform';

export class ResourceTransformer {
  private transforms = new Map<string, ResourceTransform>();

  constructor() {
    this.registerDefaultTransforms();
  }

  registerTransform = (transform: ResourceTransform): void => {
    this.transforms.set(transform.type, transform);
  };

  getResourceTypeByPath = (path: string): ResourceTransform => {
    const ext = path.split('.').pop() || '';
    return (
      Array.from(this.transforms.values()).find((t) => t.extension === `.${ext}`) || {
        type: 'text',
        extension: '.txt',
        storageFormat: 'text',
        transforms: {},
      }
    );
  };

  transformToCode = async (path: string, content: any): Promise<string> => {
    const transform = this.getResourceTypeByPath(path);
    if (transform.transforms.toCode) {
      return transform.transforms.toCode(content);
    }
    return content;
  };

  transformFromCode = async (path: string, code: string): Promise<any> => {
    const transform = this.getResourceTypeByPath(path);
    if (transform.transforms.fromCode) {
      return transform.transforms.fromCode(code);
    }
    return code;
  };

  private convertLcDocumentToJSX = (doc: LcDocument): string => {
    return `<${doc.componentName} {...${JSON.stringify(doc.props)}} />`;
  };

  private convertJSXToLcDocument = (jsx: string): LcDocument => {
    return {
      componentName: 'div',
      props: {},
    };
  };

  private convertModelToTypeScript = (model: ITypeEntity): string => {
    return `interface ${model.name} {\n  // TODO: implement\n}`;
  };

  private convertTypeScriptToModel = (ts: string): ITypeEntity => {
    return {
      name: 'NewModel',
      type: 'data',
    } as ITypeEntity;
  };

  private registerDefaultTransforms() {
    // 注册 LcDocument 转换规则
    this.registerTransform({
      type: 'lcDocument',
      extension: '.json',
      storageFormat: 'json',
      transforms: {
        toStorage: (doc: LcDocument) => JSON.stringify(doc),
        fromStorage: (content: string) => JSON.parse(content),
        toCode: (doc: LcDocument) => this.convertLcDocumentToJSX(doc),
        fromCode: (jsx: string) => this.convertJSXToLcDocument(jsx),
      },
    });

    // 注册数据模型转换规则
    this.registerTransform({
      type: 'data',
      extension: '.json',
      storageFormat: 'json',
      transforms: {
        toStorage: (model: ITypeEntity) => JSON.stringify(model),
        fromStorage: (content: string) => JSON.parse(content),
        toCode: (model: ITypeEntity) => this.convertModelToTypeScript(model),
        fromCode: (ts: string) => this.convertTypeScriptToModel(ts),
      },
    });
  }
}
